package com.wx.wxsecondskill.init;

import com.wx.redis.RedisUtils;
import com.wx.wxsecondskill.service.GoodsService;
import com.wx.wxsecondskill.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

import static com.wx.redis.constant.RedisConstant.REDIS_EXPIRE;

/**
 * @ClassName GoodsStockCountCommandLineRunner
 * @Author wx
 * @Description 启动项目时商品库存初始化
 * @Date 2018-11-19-22:16
 */
@Component
public class GoodsStockCountCommandLineRunner implements CommandLineRunner {
    /**  redis缓存商品库存可以前缀 */
    public static final String  GOODSSTOCKREFIX = "goods_count_";
    @Autowired
    private GoodsService goodsService;

    /**
     * @methodName: run
     * @author: wx
     * @description: 初始化商品库存到reids缓存、商品信息
     * @param args
     * @date: 2018/11/19
     * @return: void
     */
    @Override
    public void run(String... args) throws Exception {
        List<GoodsVo> goodsVoList = goodsService.listGoodsVo();
        if (!CollectionUtils.isEmpty(goodsVoList)){
            goodsVoList.forEach(goodsVo ->{
                //假设秒杀活动维持24小时 这里的缓存过期设置为25小时  50*30分钟
                RedisUtils.redisClient.set(GOODSSTOCKREFIX + goodsVo.getId(),goodsVo.getStockCount(),50 * REDIS_EXPIRE);
            });
        }

    }
}
